package com.hdaccp.hadoop.mr2;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class NumApp {
    public static class NumMapper extends Mapper<LongWritable,Text,LongWritable,Text>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString() ;
            System.out.println("line = " + line);
            String[] ss = line.split(" ") ;
            String s1 = ss[0] ;
            long s2 = Long.parseLong(ss[1] );
            context.write(new LongWritable(s2),new Text(s1));
        }
    }

    public  static class NumReducer extends Reducer<LongWritable,Text,LongWritable,Text>
    {
        @Override
        protected void reduce(LongWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            for(Text t:values){
                context.write(key,t);
            }
        }
    }

    public static void main(String[] args) throws  Exception{

        if(args.length<=0){
            System.err.print("请配置参数");
            System.exit(1);
        }


        //1.读取配置文件
        Configuration cfg = new Configuration() ;
        //2.产生作业
        Job job = Job.getInstance(cfg,"job2") ;
        //3.配置作业
        job.setJarByClass(NumApp.class);
        //4.1.配置作业 之 mapper
        job.setMapperClass(NumMapper.class);
        job.setMapOutputKeyClass(LongWritable.class);
        job.setMapOutputValueClass(Text.class);
        //4.2配置作业 之 mapper 目标文件
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        //5.1.配置作业 之 reducer
        job.setReducerClass(NumReducer.class);
        job.setOutputKeyClass(LongWritable.class);
        job.setOutputValueClass(Text.class);
        Path pathout = new Path(args[1]) ;
        //得到hdfs的文件系统
        FileSystem fileSystem = FileSystem.get(cfg) ;
        if(fileSystem.exists(pathout)){
            fileSystem.delete(pathout,true) ;
        }
        FileOutputFormat.setOutputPath(job,pathout);

        job.setNumReduceTasks(1);
        //6 提交作业

        System.exit(job.waitForCompletion(true)?0:1) ;
    }
}
